using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using RSPDS.MOSS.PrettyUrlController;
using System.Collections.Generic;

namespace PrettyUrlController.EventHandlers.Features
{
    public class PUCCtrlReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;
            if (null != webApp)
            {
                // Install entries in the web.config.
                SPWebService mService = SPWebService.ContentService;
                SPWebConfigModification httpModule = new SPWebConfigModification();
                httpModule.Owner = "PrettyURLController";
                httpModule.Name = "add[@name='PrettyURLController']";
                httpModule.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                httpModule.Path = "configuration/system.web/httpModules";
                httpModule.Sequence = 0;
                var t = typeof(Controller);
                httpModule.Value = String.Format("<add name='PrettyURLController' type='{0}' />", t.AssemblyQualifiedName);
                webApp.WebConfigModifications.Add(httpModule);
                webApp.Update();
                mService.ApplyWebConfigModifications();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            // Remove entries from the web.config.
            var webApp = properties.Feature.Parent as SPWebApplication;
            if (null != webApp)
            {
                // Remove any from the web app specifically.
                RemoveWebConfigEntries(webApp.WebConfigModifications);
                webApp.Update();
                // Apply the changes.
                SPWebService mService = SPWebService.ContentService;
                mService.ApplyWebConfigModifications();
            }
        }

        private static void RemoveWebConfigEntries(IList<SPWebConfigModification> mods)
        {
            var configModsFound = new List<SPWebConfigModification>();
            int modsCount1 = mods.Count;
            for (int i = modsCount1 - 1; i > -1; i--)
            {
                var mod = mods[i];
                if (mod.Owner == "PrettyURLController")
                    configModsFound.Add(mod);
            }
            while (configModsFound.Count > 0)
            {
                mods.Remove(configModsFound[0]);
                configModsFound.RemoveAt(0);
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
